package com.littlec.sdk.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.os.Environment;

import com.cmcc.groupcontacts.MainApp;
import com.littlec.sdk.business.MessageConstants;
import com.littlec.sdk.entity.AckMessage;
import com.littlec.sdk.entity.CMMessage;
import com.littlec.sdk.entity.groupinfo.GroupInfo;
import com.littlec.sdk.entity.messagebody.AudioMessageBody;
import com.littlec.sdk.entity.messagebody.GroupChangeMessageBody;
import com.littlec.sdk.entity.messagebody.ImageMessageBody;
import com.littlec.sdk.entity.messagebody.LocationMessageBody;
import com.littlec.sdk.entity.messagebody.TextMessageBody;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.littlec.sdk.utils.CMChatListener;
import com.littlec.sdk.utils.IMUserUtil;
import com.littlec.sdk.utils.MyLogger;
import com.yinhai.activity.ChatGroupActivity;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.GetUserGroupListTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.chat.Expressions;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.IMGroup;
import com.yinhai.photo.utils.Photo;
import com.yinhai.service.IMGroupServiceImpl;
import com.yinhai.service.IMUserGroupServiceImpl;
import com.yinhai.service.MsgServiceImpl;
import com.yinhai.util.ByteToString;
import com.yinhai.util.RedioUtil;
import com.yinhai.util.UuId;

public class CMPacketListener implements PacketListener {
	private MyLogger logger = MyLogger.getLogger("CMPacketListener");
	private String path = Environment.getExternalStorageDirectory().getAbsolutePath();
	private CMChatListener.CMMessageReceivedCallBack messageCallBack;
	private IMGroupServiceImpl imGroupService;
	private IMUserGroupServiceImpl imUserGroupService;
	private MsgServiceImpl msgService;
	public CMPacketListener(
			CMChatListener.CMMessageReceivedCallBack messageCallBack) {
		this.messageCallBack = messageCallBack;
		imGroupService = new IMGroupServiceImpl(MainApp.getContext());
		imUserGroupService = new IMUserGroupServiceImpl(MainApp.getContext());
		msgService = new MsgServiceImpl(MainApp.getContext());
	}

	/**
	 * 消息处理类
	 */
	public void processPacket(Packet packet){
		if (packet == null)
			return;
		if ((packet instanceof Message)) {
			Message message = (Message)packet;
			String body = message.getBody();
			//当消息体不是为空的时候
			if (message != null && message.getBody() != null
					&& !message.getBody().equals("null")) {
				//当接收到的消息不是对某条消息的回复时
				if(message.getProperty("isAnswer") ==null){
					//处理其他不是回执消息的数据
					//系统消息，如群组删除，群组修改，群添加等操作
					if((message.getProperty("systemMessage") != null) && (!message.getProperty("systemMessage").toString().equals(""))) {
						handleGroupSysMessage(message);
					} else {
						//处理聊天数据，包含单聊群聊
						handleReceivedMessage(message);
					}
				} else {
					//处理消息回执
					handleReceivedAckMessage(message);
				}
			}
		}
	}
	/**
	 * 处理聊天数据
	 */
	public void handleReceivedMessage(Message message) {
		CMMessage cmMessage = new CMMessage();
		String msgModelId = message.getProperty("msgModelId") == null?"":message.getProperty("msgModelId").toString();
		cmMessage.setUuid(msgModelId);
		cmMessage.setMessageId(UuId.getUUID());
		String type = message.getProperty("type").toString();//类型，图片，语音，坐标
		String isGroup = message.getProperty("isGroup") == null?"":message.getProperty("isGroup").toString();//1群组，0单聊
		cmMessage.setFrom(IMUserUtil.getIMUserName(message.getFrom()));
		cmMessage.setSendOrRecv(MessageConstants.Message.MSG_RECV);
		
		if(!"0".equals(isGroup)){
			//是一对一聊天
			handleReceivedMessageBody(message,cmMessage,type);
			cmMessage.setGroupInfo(new GroupInfo(message.getProperty("groupID").toString(),message.getProperty("groupName").toString(),cmMessage.getFrom()));
			cmMessage.setChatType(MessageConstants.Conversation.TYPE_GROUP);
			messageCallBack.onReceivedGroupChatMessage(cmMessage);
		} else {
			//群组聊天
			handleReceivedMessageBody(message,cmMessage,type);
			cmMessage.setChatType(MessageConstants.Conversation.TYPE_SINGLE);
			messageCallBack.onReceivedChatMessage(cmMessage);
			
		}
	}
	
	/**
	 * 处理聊天数据消息体
	 * @param message
	 * @param cmMessage
	 * @param type
	 */
	public void handleReceivedMessageBody(Message message,CMMessage cmMessage,String type) {
		if(Contact.PHOTO==Integer.valueOf((type))){
			//照片
			handleReceivedImageMessageBody(message,cmMessage);
		} else if(Contact.REDIO==Integer.valueOf((type))) {
			//语音
			handleReceivedVideoMessageBody(message,cmMessage);
		} else if(Contact.POSMAP==Integer.valueOf((type))){
			//坐标
			handleReceivedLocationMessageBody(message,cmMessage);
		} else {
			//文本
			handleReceivedTextMessageBody(message,cmMessage);
		}
	}
	/**
	 * 文本
	 * @param message
	 * @param cmMessage
	 */
	public void handleReceivedTextMessageBody(Message message,CMMessage cmMessage) {
		cmMessage.setContentType(MessageConstants.Message.TYPE_TEXT);
		cmMessage.setMessageBody(new TextMessageBody(Expressions.ReceiveTxtMsgTranslate(message.getBody())));
	}
	/**
	 * 语音
	 * @param message
	 * @param cmMessage
	 */
	public void handleReceivedVideoMessageBody(Message message,CMMessage cmMessage) {
		cmMessage.setContentType(MessageConstants.Message.TYPE_AUDIO);
		byte[] b = ByteToString.hexStringToByte(Expressions.ReceiveTxtMsgTranslate(message.getBody()));
		String fileName = path+"/"+UuId.getUUID()+".amr";
		File file = RedioUtil.getFileFromBytes(b,fileName);
		String second = message.getProperty("second")==null?"0":message.getProperty("second").toString();
		AudioMessageBody audioMessageBody = new AudioMessageBody(file,Integer.parseInt(second));
		audioMessageBody.setFileName(fileName);
		cmMessage.setMessageBody(audioMessageBody);
	}
	/**
	 * 图片
	 * @param message
	 * @param cmMessage
	 */
	public void handleReceivedImageMessageBody(Message message,CMMessage cmMessage) {
		cmMessage.setContentType(MessageConstants.Message.TYPE_PIC);
		String photoPath = Photo.getSaveIMPicPath()+message.getBody()+".png";
		String content = UrlConstant.LOCAL_URI+"getPhoto?phone=" + message.getBody();
		ImageMessageBody imageMessageBofy = new ImageMessageBody(content,content,content,content);
		cmMessage.setMessageBody(imageMessageBofy);
	}
	/**
	 * 坐标
	 * @param message
	 * @param cmMessage
	 */
	public void handleReceivedLocationMessageBody(Message message,CMMessage cmMessage) {
		String address = message.getBody();
		cmMessage.setContentType(MessageConstants.Message.TYPE_LOCATION);
		String latitude = message.getProperty("latitude")==null?"0":message.getProperty("latitude").toString();
		String longitude = message.getProperty("longitude")==null?"0":message.getProperty("longitude").toString();
		LocationMessageBody locationMessageBody = new LocationMessageBody(Double.parseDouble(latitude),Double.parseDouble(longitude),address,null);
		locationMessageBody.setOriginalUri(UrlConstant.LOCAL_URI+"getPhoto?phone=" + cmMessage.getUuid());
		cmMessage.setMessageBody(locationMessageBody);
	}
	
	/**
	 * 接收到的消息是对某条消息的回复
	 * 更新对应的聊天数据的状态，广播更新界面
	 * @param message
	 */
	public void handleReceivedAckMessage(Message message) {
		String msgModelId = message.getProperty("msgModelId")==null?"":message.getProperty("msgModelId").toString();
		AckMessage ackMessage =  new AckMessage(message.getTo(),0,msgModelId);
		ackMessage.setFrom(IMUserUtil.getIMUserName(message.getFrom()));
		messageCallBack.onReceivedAckMessage(ackMessage);
	}
	/**
	 * 处理群组系统信息，包含添加群组，删除群组，修改群组
	 * @param message
	 */
	public void handleGroupSysMessage(Message message) {
		//讨论组数据有变化
		String groupId = message.getProperty("groupId")==null?"":message.getProperty("groupId").toString();
		String groupName = message.getProperty("groupName")==null?"":message.getProperty("groupName").toString();
		String groupType = message.getProperty("groupType")==null?"":message.getProperty("groupType").toString();
		String createUserPhone = message.getProperty("createUserPhone")==null?"":message.getProperty("createUserPhone").toString();
//		GroupChangeMessageBody body = new GroupChangeMessageBody(groupId,groupName,groupType,createUserPhone);
//		CMMessage cmMessage = new CMMessage(body);
//		messageCallBack.onReceivedGroupChangeMessage(cmMessage);
		imGroupService.delete(groupId);
		imUserGroupService.deleteUserGroup(groupId);
		//删除群组
		if("0".equals(groupType)) {
//			this.msgService.delMsgModel(groupId);
			msgService.delIMListByGroup(CMChatGlobalStorage.getInstance()
					.getmLoginUserName(),
					groupId);
			CMGroupManager.getInstance().groupMembers.remove(groupId);
		} else {
			//添加修改群组
			IMGroup group = new IMGroup();
			group.setGroupId(groupId);
			group.setGroupName(groupName);
			group.setUserPhone(createUserPhone);
			imGroupService.insert(group);
			GetUserGroupListTask getUserGroupListTask = new GetUserGroupListTask(MainApp.getContext(),groupId);
			List<NameValuePair> postParam = new ArrayList<NameValuePair>();
			NameValueParam groupIdp = new NameValueParam();
			groupIdp.setName("groupId");
			groupIdp.setValue(groupId);
			postParam.add(groupIdp);
			AsyncTaskParam getUserGroupListParam = new AsyncTaskParam(UrlConstant.LOCAL_URI
					+ UrlConstant.GET_USER_GROUP_LIST);
			getUserGroupListParam.setPostParam(postParam);
			getUserGroupListTask.execute(getUserGroupListParam);
		}
	}
}
